<template>
  <div class="rolws">
    <!-- 面包屑导航 -->
    <div>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item><a href="/">权限管理</a></el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-button type="primary" plain style="margin-bottom:10px" @click="AddroleFormVisible=true">添加角色</el-button>
    <!-- 表格 -->
    <div>
      <el-table
        ref="singleTable"
        v-loading="loading"
        :data="userList"
        border
        highlight-current-row
        style="width: 100%">
        <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row v-for="grandfatheritme in scope.row.children" :key="grandfatheritme.id">
                <el-col :span="4">
                    <el-tag closable
                       @close="delsolt(scope.row,scope.row.id,grandfatheritme.id)"
                    >
                      {{grandfatheritme.authName}}
                    </el-tag>
                    <i class="el-icon-arrow-right" v-if="grandfatheritme.children.length !== 0"></i>
                </el-col>
                <el-col :span="20">
                    <el-row v-for="sontheritme in grandfatheritme.children" :key="sontheritme.id">
                      <el-col :span="4" v-if="sontheritme.children.length !== 0">
                        <el-tag type="success" closable
                          @close="delsolt(scope.row,scope.row.id,sontheritme.id)"
                        >
                          {{sontheritme.authName}}
                        </el-tag>
                        <i class="el-icon-arrow-right"></i>
                      </el-col>
                      <el-col :span="20">
                        <el-tag
                        closable type="warning"  v-for="grandsontheritme in sontheritme.children" :key="grandsontheritme.id" @close="delsolt(scope.row,scope.row.id,grandsontheritme.id)">
                          {{grandsontheritme.authName}}
                        </el-tag>
                      </el-col>
                    </el-row>
                </el-col>
              </el-row>
              <div v-if="scope.row.children.length === 0">
                <el-alert
                  title="没有角色列表,请添加"
                  type="warning">
                </el-alert>
              </div>
            </template>
        </el-table-column>
        <el-table-column
          type="index"
          width="50">
        </el-table-column>
        <el-table-column
          property="roleName"
          label="角色名称">
        </el-table-column>
        <el-table-column
          property="roleDesc"
          label="描述">
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
              <el-button type="primary" plain icon="el-icon-edit" @click="Editinfo(scope.row)"></el-button>
              <el-button type="warning" plain icon="el-icon-delete" @click="delclorInfo(scope.row)"></el-button>
              <el-button type="success" plain icon="el-icon-check" @click="Jurisdiction(scope.row)"></el-button>
           </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 角色添加弹窗 -->
    <div>
        <el-dialog title="添加角色" :visible.sync="AddroleFormVisible">
          <el-form :model="Addroleform" :rules="rules" status-icon ref="Addroleform">
            <el-form-item label="角色名字" :label-width="formLabelWidth" prop="roleName">
              <el-input v-model="Addroleform.roleName" autoComplete="off"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" :label-width="formLabelWidth" prop="roleDesc">
              <el-input v-model="Addroleform.roleDesc" autoComplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="AddroleFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="AddroleData('Addroleform')">确 定</el-button>
          </div>
        </el-dialog>
    </div>
    <!-- 编辑用户弹窗 -->
     <div>
      <el-dialog title="添加角色" :visible.sync="EditroleFormVisible">
        <el-form :model="Editroleform" :rules="rules" status-icon ref="Editrolesform">
          <el-form-item label="角色名字" :label-width="formLabelWidth" prop="roleName">
            <el-input v-model="Editroleform.roleName" autoComplete="off"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" :label-width="formLabelWidth" prop="roleDesc">
            <el-input v-model="Editroleform.roleDesc" autoComplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="EditroleFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="EditroleData('Editrolesform')">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 角色授权弹框 -->
    <div>
      <el-dialog title="角色授权" :visible.sync="JurisdictionFormVisible" class="dialog">
          <el-tree
            :data="data2"
            show-checkbox
            default-expand-all
            node-key="id"
            ref="tree"
            :default-checked-keys="seleckeys"
            :props="defaultProps">
          </el-tree>
          <div slot="footer" class="dialog-footer">
          <el-button @click="JurisdictionFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="SureJurisdiction()">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { Casting } from '@/api'
import { Delroles, AddroleInfo, EaitroleInfos, Delroleinfo, roleList, modifyUserrole } from '@/api/powerApi'
export default {
  data () {
    return {
      userList: [],
      loading: true,
      // 添加角色
      AddroleFormVisible: false, // 弹窗表格
      formLabelWidth: '80px', // 标题宽度
      Addroleform: { // 需要传递给后台的数据
        roleName: '',
        roleDesc: ''
      },
      // 编辑角色
      EditroleFormVisible: false, // 弹窗表格条件
      Editroleform: { // 需要传递给后台的数据
        roleName: '',
        roleDesc: '',
        id: ''
      },
      // 角色权限
      JurisdictionFormVisible: false,
      data2: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      // 这是选中节点的数组
      seleckeys: [],
      // 修改角色权限--保持当前角色信息
      currentInfo: {},
      // 角色表单验证
      rules: {
        roleName: [
          { required: true, message: '请输入角色名字', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  mounted () {
    this.gainData()
  },
  methods: {
    // 获取角色数据
    gainData () {
      Casting()
        .then(res => {
        // console.log(res)
          this.userList = res.data
          setTimeout(() => {
            this.loading = false
          }, 500)
        })
    },
    // 删除角色权限功能
    delsolt (row, roleId, rightId) {
      // console.log(row, roleId, rightId)
      Delroles(roleId, rightId)
        .then(res => {
          // console.log(res)
          if (res.meta.status === 200) {
            row.children = res.data
          }
        })
    },
    // 添加角色功能
    AddroleData (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          AddroleInfo(this.Addroleform)
            .then(res => {
              // console.log(res)
              if (res.meta.status === 201) {
                // 隐藏弹窗
                this.AddroleFormVisible = false
                // 重新加载页面
                this.gainData()
              }
            })
        } else {
          this.$message({
            message: '警告哦，表单校验未通过,请检查',
            type: 'warning'
          })
          return false
        }
      })
    },
    // 渲染编辑角色弹窗
    Editinfo (row) {
      this.EditroleFormVisible = true
      this.Editroleform.roleName = row.roleName
      this.Editroleform.roleDesc = row.roleDesc
      this.Editroleform.id = row.id
    },
    // 编辑角色信息
    EditroleData (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          EaitroleInfos(this.Editroleform)
            .then(res => {
              if (res.meta.status === 200) {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.EditroleFormVisible = false
                this.gainData()
              }
            })
        } else {
          this.$message({
            message: '警告哦，表单校验未通过,请检查',
            type: 'warning'
          })
          return false
        }
      })
    },
    // 删除用户
    delclorInfo (row) {
      console.log(row)
      this.$confirm('此操作将永久删除此角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Delroleinfo(row.id)
          .then(res => {
            console.log(res)
            if (res.meta.status === 200) {
              this.$message({
                type: 'success',
                message: res.meta.msg
              })
              this.gainData()
            }
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 角色权限管理表格渲染
    Jurisdiction (row) {
      // console.log(row)
      this.JurisdictionFormVisible = true
      // 发送请求获取树控文件数据
      roleList('tree')
        .then(res => {
          // console.log(res)
          if (res.meta.status === 200) {
            this.data2 = res.data
            this.currentInfo = row
            // 先把之前的默认选中的子节点清空
            this.seleckeys.length = 0
            // 三层循环获取子节点的id放到seleckeys这数组里去
            row.children.forEach(fatherChilItme => {
              if (fatherChilItme.children && fatherChilItme.children.length > 0) {
                fatherChilItme.children.forEach(sonunsChilItme => {
                  if (sonunsChilItme.children && sonunsChilItme.children.length > 0) {
                    sonunsChilItme.children.forEach(thirChilIitm => {
                      // console.log(thirChilIitm)
                      this.seleckeys.push(thirChilIitm.id)
                      // console.log(this.seleckeys)
                    })
                  }
                })
              }
            })
          }
        })
    },
    // 修改角色权限
    SureJurisdiction () {
      // console.log(this.$refs.tree.getCheckedNodes())
      let SuerJuri = this.$refs.tree.getCheckedNodes()
      let SetArr = SuerJuri.map(itme => itme.id + ',' + itme.pid)
      let repeatArr = SetArr.join(',').split(',')
      console.log(repeatArr)
      // 数组去掉重复的，用ES6中new Set的方法返回的是一个对象
      let tempArr = new Set(repeatArr)
      // 在把对象结构成数组,后台需要传递的是字符串以,隔开的，最后在把数组转换成字符串
      let newArr = [...tempArr].join(',')
      modifyUserrole(this.currentInfo.id, newArr)
        .then(res => {
          console.log(res)
          if (res.meta.status === 200) {
            this.$message({
              message: res.meta.msg,
              type: 'success'
            })
            // 再次重新渲染页面
            this.JurisdictionFormVisible = false
            this.gainData()
          }
        })
    }
  }
}
</script>

<style lang="scss" scoped>
  .rolws{
    .el-tag{
      margin: 5px;
    }
    .dialog{
      .el-tree{
        height: 400px;
        overflow: auto;
      }
    }
  }
</style>
